package com.hyts.tomcat8.execute;

import com.hyt.tomcat.api.TomcatLauncher;
import com.hyt.tomcat.bean.TomcatBean;
import com.hyt.tomcat.config.TomcatBootType;
import com.hyt.tomcat.handler.LoadConfigHandler;
import com.hyts.guava.object.Objects;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;
import java.text.MessageFormat;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.tomcat8.execute
 * author:Libo/Alex
 * create-date:2019-06-05 22:21
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: tomcat8的启动服务加载方式
 */
@Slf4j
@Builder
public class Tomcat8Launcher implements TomcatLauncher {

    private Tomcat tomcat;

    private Connector sslConnector;

    @Override
    public boolean start(TomcatBootType bootType) {
        TomcatBean tomcatBean = LoadConfigHandler.loadConfig(bootType);
        if(tomcat != null) {
            return false;
        }
        tomcat = new Tomcat();
        tomcat.setPort(Integer.parseInt(tomcatBean.getTomcatProperties().getPort()));
        try {
            //添加对应的apr协议的LifecycleListener接口
            tomcat.getServer().addLifecycleListener(new AprLifecycleListener());
            File webAppFilePath = new File(tomcatBean.getTomcatProperties().getWebappDirPath());
            if(!webAppFilePath.exists()){
                webAppFilePath.mkdirs();
            }
            tomcat.addWebapp(tomcatBean.getTomcatProperties().getContextPath(), webAppFilePath.getAbsolutePath());
            //支持外部的connector的连接器-为支持SSL/TLS认证加密机制
            if(Objects.nonNull(sslConnector)){
                tomcat.setConnector(sslConnector);
            }
            tomcat.start();
            log.info(MessageFormat.format("Tomcat开始服务运行服务contextPath：{0} - 服务监听端口:{1}",tomcatBean.getTomcatProperties().getContextPath(),
                    tomcatBean.getTomcatProperties().getPort()));
            tomcat.getServer().await();
        } catch (ServletException | LifecycleException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean stop(TomcatBean stopParam) {
        try {
            if (tomcat != null) {
                tomcat.stop();
            }
        } catch (LifecycleException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
